package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadOptions;
import com.weixin.paleituo.R;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.UpTokenBean;
import com.weixin.paleituo.bean.UpdateInfoBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.UpdataInfoEvent;
import com.weixin.paleituo.http.ApiException;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.FileUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.NetUtils;
import com.weixin.paleituo.util.PhotoUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.BottomMenuDialog;
import com.weixin.paleituo.view.CircleTransform;
import com.weixin.paleituo.view.ItemMyView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.weixin.paleituo.contans.Contans.CODE_RESULT_REQUEST;

/**
 * Author yichao
 * Time  2017/12/11 17:09
 * Dest  个人信息
 */

public class PersonInfoActivity extends BasePersonActivity {

    @BindView(R.id.tv_name_item_myfragment_layout)
    TextView mTvNameItemMyfragmentLayout;
    @BindView(R.id.iv_headico_item_activity_personinfo)
    ImageView mIvHeadicoItemActivityPersoninfo;
    @BindView(R.id.rl_headiconroot_activity_personinfo)
    RelativeLayout mRlHeadiconrootActivityPersoninfo;
    @BindView(R.id.itenmyview_nick)
    ItemMyView mItenmyviewNick;
    @BindView(R.id.itenmyview_sex)
    ItemMyView mItenmyviewSex;

    @BindView(R.id.itenmyview_myhouse)
    ItemMyView mItenmyviewMyhouse;
    private RelativeLayout mRlItemHead;
    private BottomMenuDialog mBottomMenuDialog;
    private ItemMyView mItemMyViewNikeName;
    private BottomMenuDialog mBottomMenuDialogSex;
    private Bitmap mBmp;


    private File fileUri = new File(FileUtils.IMAGE_DIR + "/photo.jpg");
    private File fileCropUri = new File(FileUtils.IMAGE_DIR+ "/crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;
    private static final int OUTPUT_X = 480;
    private static final int OUTPUT_Y = 480;
    private Dialog mLoadingDialog;
    private boolean isCancelled=false;
    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        mTvTitle.setVisibility(View.VISIBLE);
        mTvTitle.setText("我的资料");
if (BaseApplication.isLoginSuccess){

    String nickname = BaseApplication.sUserInfoBean.nickname;
    String imgurl = BaseApplication.sUserInfoBean.imgurl;
    String sex = BaseApplication.sUserInfoBean.sex;
    String signature = BaseApplication.sUserInfoBean.signature;
    setPersonInfo(imgurl, nickname, sex, signature);
}
    }
    @Override
    protected View getContentView(Context context) {
        View contentView = UIUtils.inflate(context, R.layout.activity_personinfo);


        return contentView;
    }

    public static void startActivity(Context context) {

        Intent intent = new Intent(context, PersonInfoActivity.class);
        context.startActivity(intent);
    }



    @OnClick(R.id.rl_headiconroot_activity_personinfo)
    public void onMRlHeadiconrootActivityPersoninfoClicked() {
        if (mBottomMenuDialog==null) {

            mBottomMenuDialog = new BottomMenuDialog.Builder(PersonInfoActivity.this)
                    //.setTitle("更换封面")
                    .addMenu("拍照", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mBottomMenuDialog.dismiss();


/*
                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                            startActivityForResult(intent, Contans.CAMERA_REQUEST_CODE);*/

                            imageUri = Uri.fromFile(fileUri);
                            //通过FileProvider创建一个content类型的Uri
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                imageUri = FileProvider.getUriForFile(PersonInfoActivity.this, "com.weixin.paleituo", fileUri);
                            }
                            PhotoUtils.takePicture(PersonInfoActivity.this, imageUri, Contans.CAMERA_REQUEST_CODE);
                        }
                    }).addMenu("本地相册", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mBottomMenuDialog.dismiss();
                          /*  Intent intent = new Intent(Intent.ACTION_PICK,
                                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                            startActivityForResult(intent, Contans.ALBUM_REQUEST_CODE);*/
                            PhotoUtils.openPic(PersonInfoActivity.this, Contans.GALLERY_REQUEST_CODE);
                        }
                    }).create();

        }
        if (!mBottomMenuDialog.isShowing()){

            mBottomMenuDialog.show();
        }


    }

    @OnClick(R.id.itenmyview_nick)
    public void onMItenmyviewNickClicked() {
        NikeNameActivity.startActivity(this);
    }

    @OnClick(R.id.itenmyview_sex)
    public void onMItenmyviewSexClicked() {

        mBottomMenuDialogSex = new BottomMenuDialog.Builder(PersonInfoActivity.this)
                .setTitle("性别选择")
                .addMenu("男", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mBottomMenuDialogSex.dismiss();

                        uploadHeadPic("","1","","");
                    }
                }).addMenu("女", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mBottomMenuDialogSex.dismiss();
                        uploadHeadPic("","0","","");
                    }
                }).addMenu("保密", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mBottomMenuDialogSex.dismiss();
                        uploadHeadPic("","2","","");
                    }
                }).create();

        mBottomMenuDialogSex.show();



    }

    @OnClick(R.id.itenmyview_myhouse)
    public void onMItenmyviewMyhouseClicked() {
        if (BaseApplication.sUserInfoBean.getCount() > 0){
            startActivity(MyHouseActivity.call2MyHouseActivity(this));
        }
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==RESULT_OK){
            switch (requestCode) {
                case  Contans.CAMERA_REQUEST_CODE:
                    //相机
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);

                    break;
                case Contans.GALLERY_REQUEST_CODE:
                    //相册
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(this, "com.weixin.paleituo", new File(newUri.getPath()));
                    }
                    PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);


                    break;

                case CODE_RESULT_REQUEST:
                    Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                     //   showImages(bitmap);
                     //   LogUtils.i(TAG,bitmap.toString());
                        upLoadPic(bitmap);
                    }
                    break;
            }
        }
    }

    /**
     * 上传头像
     * @param bitmap
     */
    @SuppressWarnings("unchecked")
    private void upLoadPic( Bitmap bitmap) {


        LogUtils.i(TAG,"Toke"+BaseApplication.getToken());

         final   byte[] bytes = FileUtils.bitmapToByte(bitmap);

        if (!NetUtils.NetwrokIsUseful(this)){
            ToastUtils.makeText(R.string.check_internet);
            return;
        }

        //获取上传toke
        Observable observable = ApiUtils.getApi().getQiuniToken(BaseApplication.getToken(), BaseApplication.sUserInfoBean.userId)
                .compose(RxHelper.getObservaleTransformer())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //上传
                        if (mLoadingDialog == null) {

                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(PersonInfoActivity.this, "");
                        }

                        LoadingDialogUtils.show(mLoadingDialog);

                    }
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .map(new Function<StatusCode<UpTokenBean>,String>() {
                    @Override
                    public String apply(StatusCode<UpTokenBean> upTokenBeanStatusCode) throws Exception {
                        UpTokenBean data = upTokenBeanStatusCode.getData();
                        String uptoken;
                        if (data!=null){
                            uptoken = data.getUptoken();
                                String iamgName=UIUtils.getUUidString() + ".jpg";
                            ResponseInfo responseInfo = BaseApplication.mUploadManager.syncPut(bytes, iamgName, uptoken, new UploadOptions(null, null, false, new UpProgressHandler() {
                                @Override
                                public void progress(String key, double percent) {

                                    LogUtils.i(TAG, "上传进度 ：；key  :;" + key + "   percent :::" + percent);


                                }
                            }, new UpCancellationSignal() {
                                @Override
                                public boolean isCancelled() {
                                    return isCancelled;
                                }
                            }));


                            boolean ok = responseInfo.isOK();
                            if (ok){
                              //  responseInfo.
                                return Contans.headPicUrl+iamgName;
                            }


                        }


                        return "";
                    }
                })
                .flatMap(new Function<String,Observable<StatusCode<UpdateInfoBean>>>() {
                    @Override
                    public Observable<StatusCode<UpdateInfoBean>> apply(String s) throws Exception {
                        if (StringUtils.isEmpty(s)){
                         return    Observable.error(new ApiException("上传头像失败"));

                        }else {
                            return ApiUtils.getApi().updatePersonInfo(BaseApplication.getToken(), BaseApplication.sUserInfoBean.userId, "", "", "", s);
                        }
                    }
                });

        HttpUtil.getInstance().toSubscribe(observable,new ProgressSubscriber<UpdateInfoBean>(this) {


            @Override
            protected void _onNext(StatusCode<UpdateInfoBean> t) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                UpdateInfoBean o = t.getData();
                if (o!=null){
                    LogUtils.i(TAG,"上传图片成功"+o.toString());
                    ToastUtils.makeText("上传头像成功");
                    String imgurl = o.getImgurl();
                    String nickname = o.getNickname();
                    String sex = o.getSex();
                    String signature = o.getSignature();
                    EventBus.getDefault().post(new UpdataInfoEvent(imgurl,signature,sex,nickname));

                }else {
                    ToastUtils.makeText(t.getDetailMsg()+"");
                }
            }

            @Override
            public void _onError(String message) {
                ToastUtils.makeText(message);
                LogUtils.e(TAG,"错误"+message);
                LoadingDialogUtils.closeDialog(mLoadingDialog);

            }
        },"",lifecycleSubject,false,true);



    }

    /**
     * 上传头像url
     * @param
     */
    @SuppressWarnings("unchecked")
    private void uploadHeadPic(String nick,String sex,String signature,String image) {
        Observable<StatusCode<UpdateInfoBean>> statusCodeObservable = ApiUtils.getApi().updatePersonInfo(BaseApplication.getToken(), BaseApplication.sUserInfoBean.userId, nick, sex, signature, image)
                .compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingDialog==null){
                            mLoadingDialog=LoadingDialogUtils.createLoadingDialog(PersonInfoActivity.this,"");
                        }
                        LoadingDialogUtils.show(mLoadingDialog);


                    }
                }).subscribeOn(AndroidSchedulers.mainThread());
        HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<UpdateInfoBean>(this) {

            @Override
            protected void _onNext(StatusCode<UpdateInfoBean> t) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                UpdateInfoBean o = t.getData();
                if (o!=null){
                    LogUtils.i(TAG,"上传图片成功"+o.toString());
                    String imgurl = o.getImgurl();
                    String nickname = o.getNickname();
                    String sex = o.getSex();
                    String signature = o.getSignature();
                    EventBus.getDefault().post(new UpdataInfoEvent(imgurl,signature,sex,nickname));

                }else {
                    ToastUtils.makeText(t.getDetailMsg()+"");
                }
            }

            @Override
            protected void _onError(String message) {
                ToastUtils.makeText(message);
                LogUtils.e(TAG,"错误"+message);
                LoadingDialogUtils.closeDialog(mLoadingDialog);

            }
        },"",lifecycleSubject,false,true);
    }

@Subscribe(threadMode = ThreadMode.MAIN)
public void  updataInfo(UpdataInfoEvent updataInfoEvent){

    String imgurl = updataInfoEvent.getImgurl();
    String nickname = updataInfoEvent.getNickname();
    String sex = updataInfoEvent.getSex();
    String signature = updataInfoEvent.getSignature();
    setPersonInfo(imgurl, nickname, sex, signature);

}

    /**
     * 设置个人信息
     * @param imgurl
     * @param nickname
     * @param sex
     * @param signature
     */
    private void setPersonInfo(String imgurl, String nickname, String sex, String signature) {
        if (!StringUtils.isEmpty(imgurl)){
            Glide.with(this)
                    .load(imgurl)
                    .placeholder(R.mipmap.mrtx)
                    .transform(new CircleTransform(this))
                    .into(mIvHeadicoItemActivityPersoninfo);
        }
        if (!StringUtils.isEmpty(nickname)){
            mItenmyviewNick.setDetails(nickname);
        }
        if (!StringUtils.isEmpty(sex)){
            if ("0".equals(sex)){
                mItenmyviewSex.setDetails("女");
            }else if ("1".equals(sex)){

                mItenmyviewSex.setDetails("男");
            }else if ("2".equals(sex)){

                mItenmyviewSex.setDetails("保密");
            }

        }
        if (BaseApplication.sUserInfoBean.getCount() > 0){
            mItenmyviewMyhouse.setArrowVisible(View.VISIBLE);
            mItenmyviewMyhouse.setDetails(String.valueOf(BaseApplication.sUserInfoBean.getCount()));
            mItenmyviewMyhouse.setDetailColor(ContextCompat.getColor(this,R.color.c_29CE7E));
        } else {
            mItenmyviewMyhouse.setArrowVisible(View.INVISIBLE);
            mItenmyviewMyhouse.setDetails("暂无");
            mItenmyviewMyhouse.setDetailColor(ContextCompat.getColor(this,R.color.c_616161));
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LoadingDialogUtils.closeDialog(mLoadingDialog);
        EventBus.getDefault().unregister(this);
        isCancelled=true;
    }
}
